<?php

namespace App\Helpers;
use Illuminate\Support\Facades\Log;
use Qiniu\Auth;
use Qiniu\Config;
use Qiniu\Processing\PersistentFop;
use Qiniu\Storage\BucketManager;

/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017-10-05
 * Time: 22:27
 */
class QiniuHelper
{
    private static $qiniuAuth = null;
    private static $persistentFop = null;

    public static function getAuth()
    {
        if (null === self::$qiniuAuth) {
            self::$qiniuAuth = new Auth(env('QINIU_AK'), env('QINIU_SK'));
        }
        return self::$qiniuAuth;
    }

    public static function getPersistentFop()
    {
        if (null === self::$persistentFop) {
            self::$persistentFop = new PersistentFop(self::getAuth());
        }
        return self::$persistentFop;
    }

    public static function getUploadToken($key = null, $expires = 3600, $policy = null, $strictPolicy = true)
    {
        return self::getAuth()->uploadToken(env('QINIU_BUCKET'), $key, $expires, $policy, $strictPolicy);
    }

    public static function key()
    {
        mt_srand((double)microtime()*10000);
        $charid = strtolower(md5(uniqid(rand(), true)));
        return substr($charid, 0, 8)
            .substr($charid, 8, 4)
            .substr($charid,12, 4)
            .substr($charid,16, 4)
            .substr($charid,20,12);
    }

    public static function imageKey()
    {
        return 'image_' . self::key() . self::key();
    }

    public static function videoKey()
    {
        return 'video_' . self::key() . self::key();
    }

    public static function delete($key, $type)
    {
        $config = new Config();
        $bucketManager = new BucketManager(self::getAuth(), $config);
        $err = $bucketManager->delete(env('QINIU_BUCKET'), $key);
        Log::info('删除：' . $key . ',结果：' . json_encode($err));
        switch ($type) {
            case 1:
                $err = $bucketManager->delete(env('QINIU_BUCKET'), $key . '_blur.jpg');
                Log::info('删除：' . $key . '_blur.jpg,结果：' . json_encode($err));
                $err = $bucketManager->delete(env('QINIU_BUCKET'), $key . '.jpg');
                Log::info('删除：' . $key . '.jpg,结果：' . json_encode($err));
                break;
            case 2:
                $err = $bucketManager->delete(env('QINIU_BUCKET'), $key . '.mp4');
                Log::info('删除：' . $key . '.mp4,结果：' . json_encode($err));
                $err = $bucketManager->delete(env('QINIU_BUCKET'), $key .'_thumb.jpg');
                Log::info('删除：' . $key . '_thumb.jpg,结果：' . json_encode($err));
                break;
        }

    }

    public static function fileInfo($fileName)
    {
        $config = new Config();
        $bucketManager = new BucketManager(self::getAuth(), $config);
        list($fileInfo, $err) = $bucketManager->stat(env('QINIU_BUCKET'), $fileName);
        return $fileInfo;
    }
}